package cn.example.asynctaskt;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class ProgressBarAsyT extends AppCompatActivity {
    private ProgressBar progressBar;
    private prograssBar barTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar_asy_t);

        progressBar=findViewById(R.id.mybar);
        barTask=new prograssBar();
        barTask.execute();
    }

    class prograssBar extends AsyncTask<Void,Integer,Void> {
        @Override
        protected Void doInBackground(Void... voids) {

            for (int i = 0; i < 100 ; i++) {
                if (isCancelled()){
                    break;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //progressBar.setProgress(i);
                publishProgress(i);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (isCancelled()){
                return;
            }
        }
    }

    /**
     * 判断是不是位于栈顶
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (barTask!=null&&barTask.getStatus()==AsyncTask.Status.RUNNING){
            barTask.cancel(true);
        }
    }
}
